<?php
/**
 * tpshop
 * ============================================================================
 * * 版权所有 2015-2027 深圳搜豹网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.tp-shop.cn
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * 采用最新Thinkphp5助手函数特性实现单字母函数M D U等简写方式
 * ============================================================================
 * $Author: IT宇宙人 2015-08-10 $
 */ 
namespace app\api\controller;
use app\common\logic\ActivityLogic;
use think\Db;
use think\Page;

class Activity extends Base {
    /**
     * @author dyr
     * @time 2016/09/20
     * 团购活动列表
     */
    public function group_list()
    {
        $page_size = I('page_size', 10);
        $p = I('p',1);
        $type = I('type', '');
        
        $activityLogic = new ActivityLogic();
        $groups = $activityLogic->getGroupBuyList($type, $p, $page_size);
        
        //查找广告
        $start_time = strtotime(date('Y-m-d H:00:00'));
        $end_time = strtotime(date('Y-m-d H:00:00')); 
        $adv = M("ad")->field(array('ad_link','ad_name','ad_code','media_type,pid'))->where("pid=534 AND enabled=1 and start_time< $start_time and end_time > $end_time")->find();
        if($adv && $adv['media_type'] == 4){//如果是分类, 截取最后一个分类
            $cats = explode('_',$adv['ad_link']);
            $count = count($cats);
            if($count != 0) {
                $adv['ad_link'] = $cats[$count - 1];
            }
        } 
        
        $json = array(
            'status'=>1,
            'msg'=>'获取成功',
            'result'=> [
                'groups' => $groups,
                'ad' => empty($adv) ? "" : $adv,
                'server_current_time' => time()
            ]
        );
        $this->ajaxReturn($json);
    }
    
    
    /**
     * 团购商品详情
     */
    public function group(){
    
        //$http = SITE_URL; // 网站域名
        $goods_id = I('id/d',0);
        $where['goods_id'] = $goods_id;
        $model = M('Goods');
         
        //$goods  = $model->where($where)->find(); //->field("goods_content" , true)
        $goods  = $model->field("goods_content" , true)->where($where)->find(); //
         
        // 处理商品属性
        $goods_attribute = M('GoodsAttribute')->getField('attr_id,attr_name'); // 查询属性
        $goods_attr_list = M('GoodsAttr')->where("goods_id",$goods_id)->select(); // 查询商品属性表
        foreach($goods_attr_list as $key => $val)
        {
            $goods_attr_list[$key]['attr_name'] = $goods_attribute[$val['attr_id']];
        }
        $goods['goods_attr_list'] = $goods_attr_list ? $goods_attr_list : '';
    
        // 处理商品规格
        // 商品规格 价钱 库存表 找出 所有 规格项id
        $keys = M('SpecGoodsPrice')->where("goods_id",$goods_id)->getField("GROUP_CONCAT(`key` SEPARATOR '_') ");
        if($keys)
        {
            $specImage =  M('SpecImage')->where(["goods_id" => $goods_id , 'src'=>['<>' ,'']])->getField("spec_image_id,src");// 规格对应的 图片表， 例如颜色
            $keys = str_replace('_',',',$keys);
            $sql  = "SELECT a.name,a.order,b.* FROM __PREFIX__spec AS a INNER JOIN __PREFIX__spec_item AS b ON a.id = b.spec_id WHERE b.id IN($keys) ORDER BY a.order";
            $filter_spec2 = Db::query($sql);
            foreach($filter_spec2 as $key => $val)
            {
                $filter_spec[] = array(
                    'spec_name'=>$val['name'],
                    'item_id'=> $val['id'],
                    'item'=> $val['item'],
                    'src'=>$specImage[$val['id']] ? SITE_URL.$specImage[$val['id']] : '',
                );
            }
            $goods['goods_spec_list'] = $filter_spec;
        }
    
        $goods['goods_content'] = str_replace('/'.UPLOAD_PATH, SITE_URL.'/'.UPLOAD_PATH, $goods['goods_content']);
        $goods['goods_content'] = htmlspecialchars_decode($goods['goods_content']);
        $goods['original_img'] = SITE_URL.$goods['original_img'];
        $return['goods'] = $goods;
    
        $specPrices = M('spec_goods_price')->where("goods_id", $goods_id)->getField("key,price,store_count"); // 规格 对应 价格 库存表
        // @add by wangqh 获取抢购/促销活动价格 @{
        $flashSale = get_goods_promotion($goods['goods_id']);
        if($flashSale){
            $return['goods']['shop_price'] = $flashSale['price'];
            //如果商品有促销活动, 则将改商品所有规格价格都设置为活动价
            foreach ($specPrices as $k => $v){
                $v['price'] = $flashSale['price'];
                $realSpecPrices[] = $v;
            }
        }else{
            $realSpecPrices = $specPrices;
        }
        $return['spec_goods_price']  =$realSpecPrices;
        // @}
        $return['prom'] = $flashSale; //活动信息:团购
        $return['gallery'] = M('goods_images')->field('image_url')->where(array('goods_id'=>$goods_id))->select();
        foreach($return['gallery'] as $key => $val){
            $return['gallery'][$key]['image_url'] = SITE_URL.$return['gallery'][$key]['image_url'];
        }
        //获取最近的两条评论
        $latest_comment = M('comment')->where("goods_id=:goods_id AND is_show=1 AND parent_id=0")->bind(['goods_id' => $goods_id])->limit(2)->select();
        $return['comment'] = $latest_comment ? $latest_comment : '';
    
        $goodsPrices  = M('spec_goods_price')->where("goods_id", $goods_id)->getField("key,price,store_count"); // 规格 对应 价格 库存表
        $spec_goods_price = array();
        
        $specItems =  M('spec_item')->getField("id , item");
        //根据规格ID查询规格名称
        foreach ($goodsPrices as $k => $v){
            $specIds = explode('_', $k);
            $keyName = "";
            foreach ($specIds as $idk => $idv){
                $keyName .=$specItems[$idv]." ";
            }
            $v['key_name'] = $keyName;
            $spec_goods_price[] = $v ;
        }
        $return['spec_goods_price'] = $spec_goods_price ;
        
        if(!$goods){
            $json_arr = array('status'=>-1,'msg'=>'没有该商品','result'=>'');
        }else{
            $json_arr = array('status'=>1,'msg'=>'获取成功','result'=>$return);
        }
        $this->ajaxReturn($json_arr);
    }

    /**
     * @author wangqh
     * 抢购活动时间节点
     */
    public function flash_sale_time()
    {
        $time_space = flash_sale_time_space();
        $times = array();
        foreach ($time_space as $k => $v){
            $times[] = $v;
        }
        
        $ad = M('ad')->field(['ad_link','ad_name','ad_code'])->where('pid', 2)->cache(true, TPSHOP_CACHE_TIME)->find();
        
         $return = array(
            'status'=>1,
            'msg'=>'获取成功',
            'result'=> [
                'time' => $times,
                'ad' => $ad
            ] ,
        );
        $this->ajaxReturn($return);
    }
    
 
    /**
     * @author wangqh
     * 抢购活动列表
     */
    public function flash_sale_list()
    {
        $p = I('p',1);
        $start_time = I('start_time');
        $end_time = I('end_time');
        $where = array(
            'f.start_time'=>array('egt',$start_time),
            'f.end_time'=>array('elt',$end_time)
        );
         
        $flash_sale_goods = M('flash_sale')
        ->field('f.goods_name,f.price,f.goods_id,f.price,f.item_id,g.shop_price,100*(FORMAT(f.buy_num/f.goods_num,2)) as percent , goods_num as store_count')
        ->alias('f')
        ->join('__GOODS__ g','g.goods_id = f.goods_id')
        ->where($where)
        ->page($p,10)
        ->cache(true,TPSHOP_CACHE_TIME)
        ->select();
        
        $return = array(
            'status'=>1,
            'msg'=>'获取成功',
            'result'=>$flash_sale_goods ,
        );
        $this->ajaxReturn($return);
    }
    
    /**
     * 领券列表：与手机网页版的接口一样
     */
    public function coupon_list()
    {
        $type = I('type', 1);
        $p = I('p', 1);

        $activityLogic = new ActivityLogic();
        $result = $activityLogic->getCouponList($type, $this->user_id, $p);
        $this->ajaxReturn(['status' => 1, 'msg' => '获取成功', 'result' => $result]);
    }
    
    /**
     * 领券中心
     */
    public function coupon_center()
    {
        $p = I('get.p', 1);
        $cat_id = I('get.cat_id', 0);
        
        $activityLogic = new ActivityLogic();
        $result = $activityLogic->getCouponCenterList($cat_id, $this->user_id, $p);
        
        $return = array(
            'status' => 1,
            'msg' => '获取成功',
            'result' => $result ,
        );
        $this->ajaxReturn($return); 
    }
    
    /**
     * 优惠券类型列表
     */
    public function coupon_type_list()
    {
        $p = I('get.p', 1);
        
        $activityLogic = new ActivityLogic();
        $result = $activityLogic->getCouponTypes($p, 15);

        $return = array(
            'status' => 1,
            'msg' => '获取成功',
            'result' => $result ,
        );
        $this->ajaxReturn($return); 
    }
    
    /**
     * 领取优惠券
     * 修改领取优惠券流程，增加批量领取功能
     */
    public function get_coupon()
    {
        $id = I('post.coupon_id/d', 0);
        $mobile = I('post.phone','');
        $type = I("post.type",0);

        if ($this->user_id) {
            $return = ['status' => 0, 'msg' => '请先登录','return_url'=>U('User/login')];
        }

        $activityLogic = new ActivityLogic();

        if($type == 'yes'){
            $list = D("coupon")->where('type',8)->field('id,name')->select();
            if($list != false){
                foreach ($list as $value){
                    $return = $activityLogic->get_coupon($value['id'], $this->user_id,$mobile);
                }
                $this->ajaxReturn(['status'=>1,'msg'=>'领取成功']);
            }else{
                $this->ajaxReturn(['status'=>0,'msg'=>'没有优惠券']);
            }
        }else{

            $return = $activityLogic->get_coupon($id, $this->user_id,'');
        }

        $this->ajaxReturn($return);
    }
    
 // 促销活动页面
    public function promote_list()
    {
        $pageSize = I('page_size/d' , 10);
        $goods_where['p.start_time']  = array('lt',time());
        $goods_where['p.end_time']  = array('gt',time());
        $goods_where['p.is_end']  = 0;
        $goods_where['g.prom_type']  = 3;
        $goods_where['g.is_on_sale']  = 1;
        
        $goodsCount = Db::name('goods')
        ->alias('g')
        ->join('__PROM_GOODS__ p', 'g.prom_id = p.id')
        ->join('__SPEC_GOODS_PRICE__ s','g.prom_id = s.prom_id AND s.goods_id = g.goods_id','LEFT')
        ->group('g.goods_id')
        ->where($goods_where)
        ->count('g.goods_id');
        $Page  = new Page($goodsCount,$pageSize); //分页类
        $goodsList = Db::name('goods')
            ->field('g.goods_id,g.goods_name,g.shop_price,g.click_count ,g.market_price ,p.end_time,s.item_id')
            ->alias('g')
            ->join('__PROM_GOODS__ p', 'g.prom_id = p.id')
            ->join('__SPEC_GOODS_PRICE__ s','g.prom_id = s.prom_id AND s.goods_id = g.goods_id','LEFT')
            ->group('g.goods_id')
            ->where($goods_where)
            ->limit($Page->firstRow.','.$Page->listRows)
            ->cache(true,10)
            ->select();
        $server_time = time();
        $return_list = array();
        foreach ($goodsList as $v) {
            $v["server_time"] = $server_time;
            $return_list[] = $v;
        }
        $return = array(
            'status' => 1,
            'msg' => '获取成功',
            'result' => $return_list ,
        );
        $this->ajaxReturn($return);
         
    }
    
    
    /**
     * 优惠活动
     * $author lxl
     * $time 2017-1
     */
    public function promote_goods(){
        $now_time = time();
        $where = " start_time <= $now_time and end_time >= $now_time ";
        $count = M('prom_goods')->where($where)->count();  // 查询满足要求的总记录数
        $pagesize = 10;  //每页显示数
        $Page  = new Page($count,$pagesize); //分页类
        $promote = M('prom_goods')->field('id,name as title,start_time,end_time,prom_img')->where($where)->limit($Page->firstRow.','.$Page->listRows)->select();    //查询活动列表
        $this->assign('promote',$promote);
        if(I('is_ajax')){
            return $this->fetch('ajax_promote_goods');
        }
        return $this->fetch();
    }
}